//
//  HLAccountViewModel.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/2/28.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import UIKit

class HLAccountViewModel: NSObject {

    static let shareInstance = HLAccountViewModel()
    
    var userAcount :HLUserAcoot?
    
    /// 判断用户是否已经登录
    var userLogin:Bool {
        get {
            // 这个表达式本身就是一个布尔值
            return userAcount != nil
        }
    }
    
    // 加上私有的这个标志  表示不给外部调用  外部只需要这个单例对象 就可以通过属性获取这个值
    private override init() {
        
        super.init()
        userAcount = readAcountData()
    }
    
    var filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    /// 加载账户数据
    func loadAccess_token(code:String,loadAccessTokenCallBack:(error:NSError?) ->()) {
        
        HLNeteworkTool.shareInstance.loadAccess_token(code) { (response, error) -> Void in
            
            if response == nil || error != nil {
                //回调控制器 告诉控制器获取access_token成功
                loadAccessTokenCallBack(error: error)

                return
            }
            
            self.userAcount = HLUserAcoot(dict: response as! [String:AnyObject])
            //保存用户数据
            self.saveUserAccount()
            loadAccessTokenCallBack(error: nil)
        }
    }
    
    /// 加载用户头像  和昵称
    func loadUserInform(loadUserInformBack:(error:NSError?) -> ()) {
        
        HLNeteworkTool.shareInstance.loadUserInform { (ressponse, error) -> () in
            if ressponse == nil || error != nil {
                
                loadUserInformBack(error: error)
                return
            }
            
            //保存用户数据
            let dict = ressponse as! [String:AnyObject]
            
            self.userAcount?.screen_name = dict["screen_name"] as? String
            self.userAcount?.avatar_large = dict["avatar_large"] as? String
            
            self.saveUserAccount()
            
            loadUserInformBack(error: nil)
        }
    }
    
    /// 保存用户归档数据
    private func saveUserAccount() {
        
        if userAcount != nil {
        NSKeyedArchiver.archiveRootObject(userAcount!, toFile: filePath)
        }

    }
    
    /// 读取用户归档数据
    private func readAcountData() ->HLUserAcoot? {
        // 先判断是否在有效期内
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? HLUserAcoot
        //如果没有过期就让他加载
        if account != nil  && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("读取账户数据成功:\(account?.access_token))")
            return account
        }else {
            print("读取账户数据失败")
            return nil
        }
    }
}
